/**
 * 扬尘设备运行记录dustDevRecord.js
 * 版本号： v1.0.0
 */
$(function () {
    //获取项目id
    var prId = $('#prId_').textbox('getValue');

    /**
     * 时间选中事件
     */
    $("#startDate_").datebox({
        onSelect : function(beginDate){
            $('#endDate_').datebox().datebox('calendar').calendar({
                validator: function(date){
                    return beginDate<=date;
                }
            });
        }
    });

    //查询设备编号绑定
    bindCombo_deviceId("deviceId_",prId);

    /**
     *扬尘设备运行记录列表
     */
    var lastChecked = null;
    $("#dustDevRecord_dataList").datagrid({
        fit: true,
        fitColumns: true,
        method: "POST",
        rownumbers: true,
        singleSelect: true,
        pagination: true,
        striped: true,
        border: false,
        pageSize: 10,
        pageList: [10, 30, 50, 100],
        url: CONTEXT_PATH + '/dustDevRecord/dustDevHistoricalData.do?prId='+prId,
        idField: 'ddrId',
        frozenColumns: [[
            {field: 'ddrId', checkbox: true},
            {field: 'project', title: '所属项目', width: 150, align: 'left',fixed:true,
                formatter:function(value){
                    if(value){
                        return value.prName;
                    }
                }
            },
            {field: 'dustProCheckPoint', title: '设备名称', width: 150, align: 'left',fixed:true,
                formatter:function(value){
                    if(value){
                        return value.dpcpName;
                    }
                }
            },
            {field: 'dustProCheckPoint_deviceId', title: '设备编号', width: 120, align: 'left',fixed:true,
                formatter:function(value,row){
                    if(row.dustProCheckPoint.deviceId){
                        return row.dustProCheckPoint.deviceId;
                    }
                }
            }
        ]],
        columns: [
            [
                {field: 'pm25', title: 'PM2.5(μg/m³)', width: 100, align: 'left',fixed:true},
                {field: 'pm10', title: 'PM10(μg/m³)', width: 100, align: 'left',fixed:true},
                {field: 'aqi', title: 'AQI(μg/m³)', width: 100, align: 'left',fixed:true},
                {field: 'windSpeed', title: '风速(m/s)', width: 100, align: 'left',hidden:true},
                {field: 'temperature', title: '温度(°C)', width: 100, align: 'left',hidden:true},
                {field: 'humidity', title: '湿度(%rh)', width: 100, align: 'left',hidden:true},
                {field: 'noise', title: '噪声(db)', width: 100, align: 'left',hidden:true},
                {field: 'collectTime', title: '采集时间', width: 140, align: 'left',
                    formatter:function(val) {
                        if(val){
                            return formatDatebox(val, "yyyy-MM-dd HH:mm:ss",true)
                        }
                    }
                }
            ]
        ],
        onCheck:function(rowIndex, rowData){
            var row = $("#dustDevRecord_dataList").datagrid("getChecked");
            if(row && rowIndex == lastChecked){
                $('#dustDevRecord_dataList').datagrid("unselectAll");//取消选中当前所有行
                lastChecked = null;
            }else{
                lastChecked = rowIndex;
            }
        },
        onLoadSuccess: function (data) {
            if (data.rows.length > 0) {
                lastChecked = null;
                $("#dustDevRecord_dataList").datagrid("selectRow", 0);
            }
        }
    });

    //定义可操作按钮
    $("#dustDevRecord_menu").dialog({
        title: '',
        width: 'auto',
        height: 35,
        closed: false,
        cache: false,
        inline: true,
        modal: false,
        border: false,
        toolbar: createToolbar()
    });

});

/**
 * 创建toolbar按钮组
 * @returns {Array}
 */
function createToolbar() {
    var toolbar = [];
    var falg = false;
    for(var j = 0; j < btnOptions.length; j++ ){
        if(false != btnOptions[j].value){
            falg = true;
            break;
        }
    }
    if(!falg){
        //不存在按钮
        toolbar.push({});
    }else{
        //存在按钮
        for(var i = 0; i < btnOptions.length; i++){
            if(false != btnOptions[i].value){
                //查询按钮
                if("searchBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls: "menu_search",
                        handler: function () {
                            dustDevRecord_doSearch();
                        }
                    });
                }
                //导出按钮
                if("exportBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls: "icon_export_user",
                        handler: function () {
                            dustDevRecord_export();
                        }
                    });
                }
                //详情按钮
                if("refreshBtn"  == btnOptions[i].key){
                    toolbar.push({
                        id:btnOptions[i].value.meId,
                        text:btnOptions[i].value.name,
                        iconCls:btnOptions[i].value.iconCls,
                        handler: function () {
                            dustDevRecord_view($(this).linkbutton("options").iconCls);
                        }
                    });
                }
            }
        }
    }
    return toolbar;
}

/**
 * 执行查询
 */
function dustDevRecord_doSearch() {
    var startDate = $("#startDate_").datetimebox("getValue");
    var endDate = $("#endDate_").datetimebox("getValue");
    if(startDate == null || startDate == ""){
        $.messager.show({ title: '操作提示', msg: "请选择开始时间", timeout: 3000, showType: "slide" });
        return;
    }
    if(endDate == null || endDate == ""){
        $.messager.show({ title: '操作提示', msg: "请选择结束时间", timeout: 3000, showType: "slide" });
        return;
    }
    //刷新dg页码
    refreshPageNumber("dustDevRecord_dataList");

    $("#dustDevRecord_dataList").datagrid("reload", {
        deviceId:$("#deviceId_").combobox("getValue"),
        startDate: $("#startDate_").datetimebox("getValue"),
        endDate: $("#endDate_").datetimebox("getValue")
    });
    $("#dustDevRecord_dataList").datagrid("clearSelections");
    $('#dustDevRecordQuery_dialog').dialog('close');
}

/**
 * 导出数据
 */
function dustDevRecord_export(){
    //构建数据表的二维数组的DATA
    var sheetData = [];
    //每一行的数据
    var rowData = [];
    //从页面上的表格数据中获取到数据表格的所有数据，是一个二维数据结构
    var rows = $('#dustDevRecord_dataList').datagrid("getRows");
    //数据列表为空，则不导出
    if(rows.length == 0){
        $.messager.show({ title:"操作提示", msg: "无数据可导出", timeout:3000, showType:"slide" });
        return;
    }
    //获取数据表中未冻结的所有列
    var columns = $('#dustDevRecord_dataList').datagrid("options").columns[0];
    //获取数据表中被冻结的所有列
    var frozenColumns = $('#dustDevRecord_dataList').datagrid("options").frozenColumns[0];
    //设置列表头行（描述行）
    //加载被冻结的列名
    for (var i = 0; i < frozenColumns.length; i++) {
        if(frozenColumns[i].title){
            rowData.push(frozenColumns[i].title);
        }
    }
    //加载未被冻结的列名
    for (var i = 0; i < columns.length; i++) {
        rowData.push(columns[i].title);
    }
    //将构建好的第一行描述列的数据放入二维数据表的二维数组中。
    sheetData.push(rowData);
    //遍历真实数据行
    for (var i = 0; i < rows.length; i++) {
        //将行数据置为空
        rowData = [];
        //处理列的数据，有子对象属性的做特殊处理
        for (var j = 0; j < frozenColumns.length; j++) {
            if(frozenColumns[j].field == "dustProCheckPoint"){
                if (rows[i][frozenColumns[j].field] != null) {
                    var value = rows[i][frozenColumns[j].field];
                    rowData.push(value.dpcpName.toString());
                } else {
                    rowData.push("");
                }
            }
            if(frozenColumns[j].field == "dustProCheckPoint_deviceId"){
                if (rows[i].dustProCheckPoint.deviceId != null) {
                    rowData.push(rows[i].dustProCheckPoint.deviceId.toString());
                } else {
                    rowData.push("");
                }

            }
            if(frozenColumns[j].field == "project"){
                if (rows[i][frozenColumns[j].field] != null) {
                    var value = rows[i][frozenColumns[j].field];
                    rowData.push(value.prName.toString());
                } else {
                    rowData.push("");
                }
            }
        }
        for (var j = 0; j < columns.length; j++) {
            if (rows[i][columns[j].field] != null) {
                rowData.push(rows[i][columns[j].field].toString());
            } else {
                rowData.push("");
            }
        }
        //一行数据加载完后往数据表格二维数组中push
        sheetData.push(rowData);
    }

    /* build worksheet from the grid data */
    var ws = XLSX.utils.aoa_to_sheet(sheetData);

    /* build up workbook */
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '导出数据');

    /* generate download */
    XLSX.writeFile(wb, "扬尘设备运行记录.xlsx");
}


/**
 * 查看详情
 */
function  dustDevRecord_view(iconCls) {

    var checked = $("#dustDevRecord_dataList").datagrid("getChecked");
    if (!checked || checked.length == 0) {
        $.messager.show({title: '操作提示', msg: "请选择需要查看的扬尘详情", timeout: 3000, showType: "slide"});
        return;
    }
    var row = $("#dustDevRecord_dataList").datagrid("getSelected");

    //IFRAM打开窗口
    layoutSub(yclsxq.id , yclsxq.url + row.ddrId, iconCls, yclsxq.closable, yclsxq.title);
}

function bindCombo_deviceId(deviceControl,prId){
    $.ajax({
        url: CONTEXT_PATH + "/dustProCheckPoint/getDeviceIdList.do",
        data: {prId: prId},
        type: "get",
        success: function (data) {
            var deviceCombo = [{'text': '--请选择--', 'value': ''}];
            for (var i = 0; i < data.length; i++) {
                deviceCombo.push({"text": data[i].deviceId, "value": data[i].deviceId});
            }
            $("#" + deviceControl).combobox("loadData", deviceCombo);
        }
    })
}

